<template>
  <div class="login-wrapper">
    <div class="modal">
      <a-icon type="close" @click="$emit('close-modal')" />
      <a-form-model
        ref="updatePasswordForm"
        :model="updatePasswordForm"
      >
        <h3>{{ isReset ? isEmailUpdate ? '邮箱修改' : '原密码修改' : '设置' }}密码</h3>
        <a-form-model-item v-if="isEmailUpdate" prop="email">
          <a-input
            disabled
            v-model="userInfo.email"
            placeholder="您还未绑定邮箱，请使用原密码进行修改"
            size="large"
          >
            <div slot="suffix" class="send-email-code">
              <p v-if="userInfo.email && !countdown && !sendLoading" @click="sendEmail">
                发送验证码
              </p>
              <a-icon v-if="sendLoading" type="loading" />
            </div>
          </a-input>
        </a-form-model-item>
        <a-form-model-item v-if="isEmailUpdate" prop="code">
          <a-input
            v-model="updatePasswordForm.code"
            size="large"
            placeholder="6位数字验证码"
          >
            <div slot="suffix" class="send-email-code">
              <span v-if="countdown && !sendLoading"
                >{{ countdown }} s后重新发送</span
              >
            </div>
          </a-input>
        </a-form-model-item>
        <a-form-model-item v-if="!isEmailUpdate && isReset" prop="oldpassword">
          <a-input-password
            v-model="updatePasswordForm.oldpassword"
            size="large"
            placeholder="旧密码"
          >
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item prop="newpassword">
          <a-input-password
            v-model="updatePasswordForm.newpassword"
            size="large"
            placeholder="新密码"
          >
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item prop="confirmPassword">
          <a-input-password
            v-model="updatePasswordForm.confirmPassword"
            size="large"
            placeholder="确认密码"
          >
          </a-input-password>
        </a-form-model-item>
        <a-button
          :disabled="disabledButton"
          block
          size="large"
          type="primary"
          @click="submitUpdatePassword"
          >{{ isReset ? '修改密码' : '设置密码' }}</a-button
        >
        <p class="tip" style="margin-top: 12px;" v-if="isReset">
          使用
          <span
            style="cursor: pointer"
            @click="isEmailUpdate = !isEmailUpdate"
            >{{ isEmailUpdate ? '原密码' : '邮箱' }}</span
          > 修改密码 </p>
      </a-form-model>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { encrypt } from '~/util'
export default {
  props: {
    isReset: Boolean
  },
  data () {
    return {
      updatePasswordForm: {
        code: '',
        oldpassword: '',
        newpassword: '',
        confirmPassword: ''
      },
      countdown: null,
      countdownTimer: null,
      sendLoading: false,
      isEmailUpdate: !!this.isReset
    }
  },

  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo
    }),

    disabledButton () {
      const { isEmailUpdate, updatePasswordForm, userInfo, isReset } = this
      if (!isReset) {
        return !updatePasswordForm.newpassword || !updatePasswordForm.confirmPassword
      }
      if (isEmailUpdate) {
        return !userInfo.email || !updatePasswordForm.code || !updatePasswordForm.newpassword || !updatePasswordForm.confirmPassword
      } else {
        return !updatePasswordForm.newpassword || !updatePasswordForm.confirmPassword || !updatePasswordForm.oldpassword
      }
    }
  },

  beforeDestroy () {
    clearInterval(this.countdownTimer)
  },

  methods: {
    /**
     * change user password
     */
    async submitUpdatePassword () {
      if (!this.disabledButton) {
        const { oldpassword, newpassword, confirmPassword } = this.updatePasswordForm
        if (newpassword !== confirmPassword) {
          return this.$message.info('两次输入的密码不一致')
        }
        try {
          const { aesKey, aesIv } = (await this.$axios.get('/gimishare/api/v1/unit/getpublickey')).data
          const requestParams = {
            ...this.updatePasswordForm,
            oldpassword: encrypt(oldpassword, aesKey, aesIv),
            newpassword: encrypt(newpassword, aesKey, aesIv),
            confirmPassword: encrypt(confirmPassword, aesKey, aesIv),
            email: this.userInfo.email,
            type: this.isReset ? this.isEmailUpdate ? '0' : '1' : '2'
          }
          await this.$axios.post('/gimishare/api/v1/users/updatepassword', requestParams)
          this.$message.success(this.isReset ? '修改密码成功' : '设置密码成功')
          const { data } = await this.$axios.get('/gimishare/api/v1/users/sessionuserinfo')
          this.$store.commit('UPDATE_USER_INFO', data)
          this.$emit('close-modal')
        } catch (error) {
          console.log(error)
        }
      }
    },

    /**
     * send email
     */
    async sendEmail () {
      const REG_EMAIL = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!REG_EMAIL.test(this.userInfo.email)) {
        return this.$message.info('邮箱格式不正确')
      }
      this.sendLoading = true
      try {
        await this.$axios.get(
          `/gimishare/api/v1/unit/emailcode?email=${this.userInfo.email}`
        )
        this.sendLoading = false
        this.countdown = 60
        this.countdownTimer = setInterval(() => {
          this.countdown--
          if (this.countdown === 0) {
            this.countdown = null
            clearInterval(this.countdownTimer)
          }
        }, 1000)
      } catch (error) {
        this.sendLoading = false
        console.log(error)
      }
    }
  }
}
</script>
